import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:google_mlkit_commons/google_mlkit_commons.dart';
import 'package:image_picker/image_picker.dart';

/// 检查当前是否为鸿蒙平台
bool isHarmonyOS() {
  return Platform.isOhos ;
}

class CommonsDemoView extends StatefulWidget {
  @override
  State<CommonsDemoView> createState() => _CommonsDemoViewState();
}

class _CommonsDemoViewState extends State<CommonsDemoView> {
  String? _currentDemo;
  String? _outputText;
  File? _selectedImage;
  InputImage? _inputImage;
  final ImagePicker _picker = ImagePicker();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google ML Kit Commons Demo'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // Demo Selection
              DropdownButtonFormField<String>(
                value: _currentDemo,
                decoration: InputDecoration(
                  labelText: 'Select Demo',
                  border: OutlineInputBorder(),
                ),
                items: [
                  DropdownMenuItem(value: 'fromFile', child: Text('InputImage.fromFile')),
                  DropdownMenuItem(value: 'fromFilePath', child: Text('InputImage.fromFilePath')),
                  DropdownMenuItem(value: 'fromBytes', child: Text('InputImage.fromBytes')),
                  DropdownMenuItem(value: 'fromMediaImage', child: Text('InputImage.fromMediaImage')),
                  DropdownMenuItem(value: 'rectJson', child: Text('RectJson Extension')),
                  DropdownMenuItem(value: 'getPlatformVersion', child: Text('Get Platform Version')),
                  DropdownMenuItem(value: 'getInputImage', child: Text('Get InputImage')),
                  DropdownMenuItem(value: 'modelManager', child: Text('ModelManager APIs')),
                ],
                onChanged: (value) {
                  setState(() {
                    _currentDemo = value;
                    _outputText = null;
                  });
                },
              ),
              SizedBox(height: 16),

              // Image Selection
              if (_currentDemo != null &&
                  (_currentDemo!.contains('fromFile') ||
                      _currentDemo!.contains('fromFilePath') ||
                      _currentDemo!.contains('fromBytes') ||
                      _currentDemo == 'getInputImage'))
                Column(
                  children: [
                    ElevatedButton(
                      onPressed: () => _getImage(ImageSource.gallery),
                      child: Text('Select Image from Gallery'),
                    ),
                    SizedBox(height: 8),
                    if (_selectedImage != null)
                      Container(
                        margin: EdgeInsets.all(8),
                        height: 200,
                        child: Image.file(_selectedImage!),
                      ),
                  ],
                ),
              SizedBox(height: 16),

              // Execute Button
              ElevatedButton(
                onPressed: _currentDemo != null ? _executeDemo : null,
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(vertical: 12),
                ),
                child: Text('Execute Demo'),
              ),
              SizedBox(height: 16),

              // Output Display
              if (_outputText != null)
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey),
                    borderRadius: BorderRadius.circular(4),
                    color: Colors.grey[50],
                  ),
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Text(_outputText!),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _getImage(ImageSource source) async {
    try {
      final pickedFile = await _picker.pickImage(source: source);
      if (pickedFile != null) {
        setState(() {
          _selectedImage = File(pickedFile.path);
        });
      }
    } catch (e) {
      setState(() {
        _outputText = 'Error picking image: $e';
      });
    }
  }

  Future<void> _executeDemo() async {
    if (_currentDemo == null) return;

    try {
      switch (_currentDemo) {
        case 'fromFile':
        // 测试InputImage.fromFile构造方法
          if (_selectedImage == null) {
            _outputText = 'Please select an image first';
            break;
          }

          try {
            _outputText = 'Creating InputImage from file...\n';
            _inputImage = InputImage.fromFile(_selectedImage!);
            _outputText = '${_outputText!}Success!\n';
            _outputText = '${_outputText!}Image info:\n';
            _outputText = '${_outputText!}- File path: ${_inputImage!.filePath}\n';
            if (_inputImage!.metadata != null) {
              _outputText = '${_outputText!}- Width: ${_inputImage!.metadata?.size.width}\n';
              _outputText = '${_outputText!}- Height: ${_inputImage!.metadata?.size.height}\n';
              _outputText = '${_outputText!}- Rotation: ${_inputImage!.metadata?.rotation}\n';
            }
          } catch (e) {
            _outputText = 'Error creating InputImage: $e';
          }
          break;

        case 'fromFilePath':
        // 测试InputImage.fromFilePath构造方法
          if (_selectedImage == null) {
            _outputText = 'Please select an image first';
            break;
          }

          try {
            _outputText = 'Creating InputImage from file path...\n';
            _inputImage = InputImage.fromFilePath(_selectedImage!.path);
            _outputText = '${_outputText!}Success!\n';
            _outputText = '${_outputText!}Image info:\n';
            _outputText = '${_outputText!}- File path: ${_inputImage!.filePath}\n';
            if (_inputImage!.metadata != null) {
              _outputText = '${_outputText!}- Width: ${_inputImage!.metadata?.size.width}\n';
              _outputText = '${_outputText!}- Height: ${_inputImage!.metadata?.size.height}\n';
              _outputText = '${_outputText!}- Rotation: ${_inputImage!.metadata?.rotation}\n';
            }
          } catch (e) {
            _outputText = 'Error creating InputImage: $e';
          }
          break;

        case 'fromBytes':
        // 测试InputImage.fromBytes构造方法
          if (_selectedImage == null) {
            _outputText = 'Please select an image first';
            break;
          }

          try {
            _outputText = 'Creating InputImage from bytes...\n';
            final bytes = _selectedImage!.readAsBytesSync();

            // 根据平台选择合适的格式
            InputImageFormat format;
            if (isHarmonyOS()) {
              format = InputImageFormat.bgra8888;
            } else if (Platform.isAndroid) {
              format = InputImageFormat.nv21;
            } else {
              format = InputImageFormat.bgra8888;
            }

            _inputImage = InputImage.fromBytes(
              bytes: bytes,
              metadata: InputImageMetadata(
                size: Size(640, 480), // 假设的尺寸
                rotation: InputImageRotation.rotation0deg, // 使用枚举类型
                format: format,
                bytesPerRow: 640 * 4,
              ),
            );

            _outputText = '${_outputText!}Success!\n';
            _outputText = '${_outputText!}Image info:\n';
            _outputText = '${_outputText!}- Bytes length: ${bytes.length}\n';
            if (_inputImage!.metadata != null) {
              _outputText = '${_outputText!}- Width: ${_inputImage!.metadata?.size.width}\n';
              _outputText = '${_outputText!}- Height: ${_inputImage!.metadata?.size.height}\n';
              _outputText = '${_outputText!}- Rotation: ${_inputImage!.metadata?.rotation}\n';
              _outputText = '${_outputText!}- Format: ${_inputImage!.metadata?.format}\n';
              _outputText = '${_outputText!}- Bytes per row: ${_inputImage!.metadata?.bytesPerRow}\n';
            }
          } catch (e) {
            _outputText = 'Error creating InputImage: $e';
          }
          break;

        case 'fromMediaImage':
        // 测试InputImage.fromMediaImage构造方法（在实际应用中需要相机预览）
          _outputText = 'InputImage.fromMediaImage演示需要相机预览上下文，\n';
          _outputText = '${_outputText!}在实际应用中，您需要从相机控制器获取SurfaceImage或类似对象。\n';
          _outputText = '${_outputText!}\n示例代码：\n';
          _outputText = '${_outputText!}// final mediaImage = await cameraController.takePicture();\n';
          _outputText = '${_outputText!}// final image = InputImage.fromMediaImage(\n';
          _outputText = '${_outputText!}//   mediaImage.image,\n';
          _outputText = '${_outputText!}//   InputImageMetadata(\n';
          _outputText = '${_outputText!}//     size: Size(mediaImage.width.toDouble(), mediaImage.height.toDouble()),\n';
          _outputText = '${_outputText!}//     rotation: rotationDegrees,\n';
          _outputText = '${_outputText!}//     format: platformFormat,\n';
          _outputText = '${_outputText!}//     bytesPerRow: bytesPerRow,\n';
          _outputText = '${_outputText!}//   ),\n';
          _outputText = '${_outputText!}// );';
          break;

        case 'rectJson':
        // 测试RectJson扩展
          try {
            _outputText = 'Testing RectJson extension...\n\n';

            // 创建一个JSON格式的Rect对象
            final rectJson = {
              'left': 10.0,
              'top': 20.0,
              'right': 110.0,
              'bottom': 170.0,
            };

            // 从JSON转换为Rect
            final rectFromJson = RectJson.fromJson(rectJson);

            // 测试无效JSON
            final invalidRectJson = {'x': 'invalid', 'y': 0, 'width': 0, 'height': 0};
            final invalidRect = RectJson.fromJson(invalidRectJson);

            _outputText = '${_outputText!}JSON representation: $rectJson\n';
            _outputText = '${_outputText!}Converted to Rect: $rectFromJson\n\n';
            _outputText = '${_outputText!}Invalid JSON: $invalidRectJson\n';
            _outputText = '${_outputText!}Converted to Rect (defaults to 0,0,0,0): $invalidRect\n\n';
            _outputText = '${_outputText!}Usage:\n';
            _outputText = '${_outputText!}// 从ML Kit API结果中解析矩形区域\n';
            _outputText = '${_outputText!}final rect = RectJson.fromJson(jsonMap);\n';
            _outputText = '${_outputText!}// 然后可以使用这个rect对象进行绘制或其他操作';
          } catch (e) {
            _outputText = 'Error testing RectJson: $e';
          }
          break;

        case 'getPlatformVersion':
        // 根据detector_view.dart的方式，这里可以展示如何在实际应用中获取平台版本
          _outputText = '在实际应用中，平台版本通常通过特定平台的API获取\n\n';
          _outputText = '${_outputText!}示例代码：\n';
          _outputText = '${_outputText!}// 对于Android\n';
          _outputText = '${_outputText!}// import "package:device_info_plus/device_info_plus.dart";\n';
          _outputText = '${_outputText!}// final deviceInfo = DeviceInfoPlugin();\n';
          _outputText = '${_outputText!}// final androidInfo = await deviceInfo.androidInfo;\n';
          _outputText = '${_outputText!}// final version = androidInfo.version.release;\n\n';
          _outputText = '${_outputText!}// 对于iOS\n';
          _outputText = '${_outputText!}// final iosInfo = await deviceInfo.iosInfo;\n';
          _outputText = '${_outputText!}// final version = iosInfo.systemVersion;\n\n';
          _outputText = '${_outputText!}// 对于鸿蒙平台\n';
          _outputText = '${_outputText!}// 可以通过特定的API检查是否为鸿蒙平台\n';
          _outputText = '${_outputText!}final isHarmonyOSPlatform = isHarmonyOS();\n';
          _outputText = '${_outputText!}Current platform: ${Platform.operatingSystem} ${isHarmonyOS() ? '(HarmonyOS)' : ''};';
          break;

        case 'getInputImage':
        // 测试如何获取和处理InputImage对象
          if (_selectedImage == null) {
            _outputText = 'Please select an image first';
            break;
          }

          try {
            _outputText = '获取和处理InputImage对象...\n';

            // 从文件创建InputImage
            _inputImage = InputImage.fromFile(_selectedImage!);

            // 获取图像信息
            _outputText = '${_outputText!}Success!\n';
            _outputText = '${_outputText!}InputImage信息:\n';
            _outputText = '${_outputText!}- 文件路径: ${_inputImage!.filePath}\n';
            if (_inputImage!.metadata != null) {
              _outputText = '${_outputText!}- 宽度: ${_inputImage!.metadata?.size.width}\n';
              _outputText = '${_outputText!}- 高度: ${_inputImage!.metadata?.size.height}\n';
              _outputText = '${_outputText!}- 旋转角度: ${_inputImage!.metadata?.rotation}\n';
            }

            _outputText = '${_outputText!}\n这个InputImage对象可以传递给其他ML Kit检测器使用：\n';
            _outputText = '${_outputText!}// 例如，传递给条码扫描器\n';
            _outputText = '${_outputText!}// final barcodeScanner = BarcodeScanner();\n';
            _outputText = '${_outputText!}// final barcodes = await barcodeScanner.processImage(_inputImage!);\n';
          } catch (e) {
            _outputText = '处理InputImage时出错: $e';
          }
          break;

        case 'modelManager':
        // 演示ModelManager的使用方法
          _outputText = 'ModelManager API 演示\n\n';
          _outputText = '${_outputText!}ModelManager用于管理ML Kit模型的下载、删除和检查状态\n\n';
          _outputText = '${_outputText!}在实际应用中，ModelManager通常由具体的检测器提供：\n\n';
          _outputText = '${_outputText!}示例代码：\n';
          _outputText = '${_outputText!}// 对于图像标签检测器\n';
          _outputText = '${_outputText!}// final modelManager = ImageLabelerModelManager();\n';
          _outputText = '${_outputText!}// await modelManager.downloadModel(modelPath);\n';
          _outputText = '${_outputText!}// final isDownloaded = await modelManager.isModelDownloaded(modelPath);\n';
          _outputText = '${_outputText!}// await modelManager.deleteModel(modelPath);\n\n';
          _outputText = '${_outputText!}// 对于鸿蒙平台\n';
          _outputText = '${_outputText!}// 确保使用适配鸿蒙的模型和API';
          break;
      }
    } catch (e) {
      _outputText = 'Error: $e';
    }

    setState(() {});
  }
}